package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;

import com.jt.util.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.ShardedJedis;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired
    private JedisCluster jedis;
    @Override
    public ItemCat findItemCatName(Long itemCatId) {
        return itemCatMapper.selectById(itemCatId);
    }
// 在引入redis缓存管理机制，来减少数据访问次数，提高速度后，这个方法已经被下面的方法使用，并与
//    下面的 findItemCatCache方法合二为一
    @Override
    public List<EasyUITree> findItemCatList(long parentId) {
        List<EasyUITree> treeList=new ArrayList<>();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("parent_id", parentId);
        List<ItemCat> catList=itemCatMapper.selectList(queryWrapper);

        for (ItemCat itemCat:catList){
            long id=itemCat.getId();
            String text=itemCat.getName();
            String state=itemCat.getIsParent()?"closed":"open";
            EasyUITree easyUITree=new EasyUITree(id,text,state);
            treeList.add(easyUITree);
        }
        return treeList;
    }

    @Override
    @CacheFind(key = "ITEMCAT_PARENTID")
    public List<EasyUITree> findItemCatCache(long parentId) {




//        定义一个键值对，键恒为
        String key="ITEMCAT_PARENTID::"+parentId;
        List<EasyUITree> treeList=new ArrayList();
        if (jedis.exists(key)){
            String json=jedis.get(key);
            treeList= ObjectMapperUtil.toObj(json, treeList.getClass());
            System.out.println("查询redis缓存");
        }else {
            treeList=findItemCatList(parentId);
            String json=ObjectMapperUtil.toJSON(treeList);
            jedis.set(key,json);
            System.out.println("查询数据库");

        }

        return treeList;
    }
}
